//
//  AMOauthViewController.swift
//  微博
//
//  Created by zhc on 15/11/26.
//  Copyright © 2015年 zhc. All rights reserved.
//

import UIKit
import SVProgressHUD

class AMOauthViewController: UIViewController {

    
    override func loadView() {
        view=webView;
        
        webView.delegate=self;
        
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //jiazai
        
        // 加载授权界面
        let request = NSURLRequest(URL: AMTools.sharedInstance.oauthURL())
        webView.loadRequest(request)
        
        // 设置导航栏
        // 左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        // 右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        
        
        
    }

    /// 关闭控制器
    func close() {
        // 关闭SV
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
 
    /// 填充账号
    func autoFill() {
        // 创建js代码
        let js = "document.getElementById('userId').value='3319380@163.com'; document.getElementById('passwd').value='zhc1992';"
        // 让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //加载accessToken
    func loadAccessToken(code:String){
    
       AMTools.sharedInstance.loadAccessToken(code)
    
    }
    
    
    
    
    
    

   private lazy var webView = UIWebView()
    
    
   
   
}






extension AMOauthViewController:UIWebViewDelegate{
    
    /// webView开始加载链接
    func webViewDidStartLoad(webView: UIWebView) {
        // showWithStatus只有没有主动关闭,一直显示
        // showInfoWithStatus 过段时间就消失
        SVProgressHUD.showWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)
        
     
    }
    
    /// webView加载完成某个链接
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        print("urlString: \(urlString)")
        
        // 点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // 点击授权:
        // 当用户点击取消或同意,拦截,不让它加载,我们来处理
        if !urlString.hasPrefix(AMTools.sharedInstance.redirect_uri) {
            
            // 其他情况, 直接加载
            return true
        }
        
        // 点击取消 或 点击授权
        // 判断url地址里面是以code=开头,截取code= 后面的字符串
        // error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // code=57c4568b41da3e3fed3541758b804f8a
        if let query = request.URL?.query {
            //http://www.baidu.com/?code=78ea2a88d6ee9d1f968b7036576c1521
            //        print("query: \(query)")
            let codeString = "code="
            // 判断是否是以code=开头
            if query.hasPrefix(codeString) {
                // 点击授权, 截取code的值
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("code:\(code)")
                
                // 加载accessToken
                loadAccessToken(code)
                
            } else {
                // 点击取消
                print("点击取消")
                self.close()
            }
        }
        
        // 不去加载授权回调地址
        return false
    }
    
    
    
    
    
    
    
}










